'use strict'

//初始化调用
let http = require('http');
let path = require('path');
let fs = require('fs');


//获取文件路径方法
function getPath(fullpath){
    //默认状态404
    let filePath = '404';
    //判断路径是否正确
    if(fs.existsSync(fullpath)){
        //判断文件是否存在
        if(fs.statSync(fullpath).isFile()){
            return fullpath;
        }else{
            //遍历目录
            fs.readdirSync(fullpath).forEach((x)=>{
                let filename = path.join(fullpath,x);
                    //判断文件是否存在
                    if(fs.statSync(filename).isFile()){
                        filePath=filename;
                        return;
                    }
            })
        }
    }
    return filePath;
}



//http服务
let server = http.createServer((req,res)=>{
    let url = req.url;
    let workspace = path.resolve('.');
    
    let fullpath = path.join(workspace,url);
    let show = getPath(fullpath);
    console.log(show);
    if(show!=='404'){
        fs.createReadStream(show).pipe(res);
    }else{
        res.writeHead(404);
        res.write('<head><meta charset="utf8"></head>');
        res.end('错了！！！')
    }
})


//端口
let port = 3030;

server.listen(port);

//调用
console.log(`http://127.0.0.1:${port}`);


// 'use strict'

// let http = require('http');
// let fs = require('fs');
// let path = require('path');


// function getPath(fullPath){
//     let filePath = '404';
//     if(fs.existsSync(fullPath)){
//         if(fs.statSync(fullPath).isFile()){
            
//             return fullPath;
//         }else{
//             fs.readdirSync(fullPath).forEach(x=>{
//                 let fileName = path.join(fullPath,x);
//                 filePath=fileName;
//                 return ;
//             })
//         }
//     }
//     return filePath;
// }

// http.createServer(function (req, res) {
//     let workSpace = path.resolve('.');
//     let rePath = req.url;

//     let fullPath = path.join(workSpace,rePath);

//     let show = getPath(fullPath);
//     console.log(show);
//     if(show!=='404'){
//         fs.createReadStream(show).pipe(res);
//     }else{
//         res.writeHead(404);
//         res.write('<head><meta charset = "utf8"></meta></head>');
//         res.end('错了！！！');
//     }

// }).listen(8081);

// console.log('Server running at http://127.0.0.1:8081/');